//
//  HROAuthViewController.swift
//  微博
//
//  Created by 众力金融 on 2017/1/12.
//  Copyright © 2017年 众力金融. All rights reserved.
//

import UIKit
import SVProgressHUD

class HROAuthViewController: UIViewController {

    fileprivate lazy var webview = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
  
        SVProgressHUD.show()
        view = webview
        view.backgroundColor = UIColor.white
        //
        webview.scrollView.isScrollEnabled = false
        
        webview.delegate = self
        
        //设置导航栏
        title = "登录新浪微博"
        //导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        
        //加载授权界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        print("urlString~~\(urlString)")
        guard let url = URL(string: urlString) else {
            return
        }
        //简历请求
        let request = URLRequest(url: url)
        //加载请求
        webview.loadRequest(request)
      
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK: - 监听方法
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
     dismiss(animated: true, completion: nil)
    }
    /// 自动填充 - webview 的注入 直接通过 js 修改 本地浏览器中 缓存的页面内容
    /// 点击登录按钮 执行 submit() 将本地的数据提交给服务器
    @objc fileprivate func autoFill() {
        //准备js
        //document.getElementById("userId").value = "18501201551";
        //document.getElementById("passwd").value = "han123456";
        let js = "document.getElementById('userId').value = '18501201551';" + "document.getElementById('passwd').value = 'han123456';"
        //让webview 执行js
        webview.stringByEvaluatingJavaScript(from: js)
    }

}

extension HROAuthViewController: UIWebViewDelegate {
   
    //https://m.baidu.com/?code=b0ab711eedc301796cd9f63d9670bc99&from=844b&vit=fps
    //code=b0ab711eedc301796cd9f63d9670bc99&from=844b&vit=fps
    //"https://m.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330&from=844b&vit=fps"
    /// webview 将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webview
    ///   - request: 要加载的请求
    ///   - navigationType: 导航
    /// - Returns: 是否加载 request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //request.url?.absoluteString.hasPrefix(WBRedirectURL) 返回的是可选项 true false nil
        if request.url?.absoluteString.hasPrefix(WBRedirectURL) == false {
            return true
        }
        print("加载请求 ---- \(request.url?.absoluteString)")
        //query 就是URL中 ? 后面的所有部分
        print("加载请求---\(request.url?.query)")
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            return false
        }
        
        //从 query 字符串取出 授权码 
        //代码走到此处 url 中一定有 查询字符串 并且 包涵 code
        //从https://m.baidu.com 回调地址查询的字符串查找 code=
        //如果有 授权成功 否则失败
      let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("code ~~ \(code)")
        print("获取授权码...")
        //使用授权码
        HRNetworkManager.shared.loadaccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else {
                 SVProgressHUD.showInfo(withStatus: "登录成功")
            }
            //下一步 跳转界面 通过通知发送登录成功的消息
            //1.发送通知
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessdNotification), object: nil)
            //关闭窗口
            self.close()
        }
        return false
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
